
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style type="text/css">
    .grid {
      margin: auto;
      width: 600px;
      text-align: center;
    }
    .grid table {
      width: 100%;
      border-collapse: collapse;
    }
    .grid th,td {
      padding: 10;
      border: 1px dashed orange;
      height: 35px;
      line-height: 35px;
    }
    .grid th {
      background-color: orange;
    }
  </style>


</head>
<body>
  <div id="app">
    <input type="text" v-model='name'>
    <button @click='addBook'>{{btnVal}}</button>
    <div class="grid">
      <table>
        <thead>
          <tr>
            <th>编号</th>
            <th>名称</th>
            <th>时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr :key='item.id' v-for='item in books'>
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
            <td>{{item.date}}</td>
            <td>
              <a href="#" @click.prevent='editBook(item.id,item.name)'>修改</a>
              <span>|</span>
              <a href="#" @click.prevent='deleteData(item.id)'>删除</a>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
  <script type="text/javascript" src="./vue.js"></script>
  <script type="text/javascript">
    /*
      图书管理-图书列表展示功能
      注意事项：<a href="" @click.prevent>修改</a>
      事件绑定时，可以只添加修饰符，而不绑定事件函数
    */
    var vm = new Vue({
      el: '#app',
      data: {
        books: [],
        name:'',
        btnVal:'添加',
        flag:false,
        currentId:''
      },
      methods:{
        deleteData(i) {
          this.books = this.books.filter(item=> item.id != i)
        },
        addBook() {
          if(!this.flag) {
            let id = this.books[this.books.length -1].id + 1
            let obj = {
            "id": id,
            "name": this.name,
            "date":""
          } 
            this.books.push(obj)
            this.name = ''
          } else {
            this.books.filter((item)=>{
              if(item.id == this.currentId) {
                item.name = this.name
              }
              return true
            })
            this.name = ''
            this.flag = false;
            this.btnVal = '添加图书'
          }
          
        },

        editBook(i,n) {
          this.currentId = i
          this.name = n
          this.flag = true
          this.btnVal = '修改图书'
        }
      },
      mounted() {
     
         fetch("./data/books.json").then(res=>res.json())
        .then(res=>{
                this.books = res
            }) 
    }
    });
  </script>
</body>
</html>
